package service

import (
	"CartApp/dao/mysql"
	"CartApp/models"
	"CartApp/pkg/e"
	"CartApp/serializer"
	"time"

	"github.com/jinzhu/gorm"
	logging "github.com/sirupsen/logrus"
)

func CreatePost(id uint, post *models.CreatePost) *serializer.Response {
	postData := models.Post{
		Uid:       id,
		Title:     post.Title,
		Content:   post.Content,
		Status:    0,
		StartTime: time.Now().Unix(),
	}
	code := e.SUCCESS
	err := mysql.DB.Create(&postData).Error
	if err != nil {
		logging.Info(err)
		code = e.ErrorDatabase
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
			Error:  err.Error(),
		}
	}
	return &serializer.Response{
		Status: code,
		Data:   serializer.BuildPost(postData),
		Msg:    e.GetMsg(code),
	}

}

// 更新post
func UpdatePost(p *models.Post) *serializer.Response {
	//Where("id = ?", p.ID)
	err := mysql.DB.Debug().Model(&models.Post{}).Where(&models.Post{
		Model: gorm.Model{ID: p.ID},
	}).Updates(
		map[string]interface{}{
			"title":   p.Title,
			"content": p.Content,
		},
	).Error

	code := e.SUCCESS
	if err != nil {
		logging.Info(err)
		code = e.ErrorDatabase
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
			Error:  err.Error(),
		}
	}
	return &serializer.Response{
		Status: code,
		Msg:    e.GetMsg(code),
		Data:   "修改成功",
	}

}

func GetPost(id int64) *serializer.Response {
	p := new(models.Post)
	u := new(models.User)
	code := e.SUCCESS
	err := mysql.DB.First(&p, id).Error
	mysql.DB.First(&u, p.Uid)
	p.User = u.UserName
	if err != nil {
		logging.Info(err)
		code = e.ErrorDatabase
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
			Error:  err.Error(),
		}
	}
	return &serializer.Response{
		Status: code,
		Data:   serializer.BuildPost(*p),
		Msg:    e.GetMsg(code),
	}

}

//post 查询列表
func PostList(id uint, service *serializer.ListPostService) serializer.Response {
	var posts []models.Post
	total := 0
	mysql.DB.Model(models.Post{}).Where("uid = ?", id).Count(&total).
		Limit(service.Limit).Offset((service.Size - 1) * service.Limit).
		Find(&posts)

	return serializer.BuildListResponse(serializer.BuildPosts(posts), uint(total))

}

// 用户与post 之间的关系数据
func UserPostList(service *serializer.ListPostService) *serializer.Response {
	var users []models.User
	total := 0
	code := e.SUCCESS
	err := mysql.DB.Model(models.User{}).Preload("Post").Count(&total).
		Limit(service.Limit).Offset((service.Size - 1) * service.Limit).
		Find(&users).Error
	if err != nil {
		logging.Info(err)
		code = e.ErrorDatabase
		return &serializer.Response{
			Status: code,
			Msg:    e.GetMsg(code),
			Error:  err.Error(),
		}
	}
	return &serializer.Response{
		Status: code,
		Data:   users,
		Msg:    e.GetMsg(code),
	}
}
